﻿namespace MiddlewareTestWebApp
{
    public class MyStaticFilesMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IWebHostEnvironment _hostEnv;

        public MyStaticFilesMiddleware(RequestDelegate next, IWebHostEnvironment hostEnv)
        {
            _next = next;
            _hostEnv = hostEnv;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            string path = context.Request.Path.Value ?? "";
            var file = _hostEnv.WebRootFileProvider.GetFileInfo(path);
            if (!file.Exists || !ContentTypeHelper.IsValid(file))
            {
                await _next(context);
                return;
            }
            context.Response.ContentType = ContentTypeHelper.GetContentType(file);
            context.Response.StatusCode = 200;
            using var stream = file.CreateReadStream();
            var bytes = await ToArrayAsync(stream);
            await context.Response.Body.WriteAsync(bytes, 0, bytes.Length);
        }

        private static async Task<byte[]> ToArrayAsync(Stream stream)
        {
            using var ms = new MemoryStream();
            await stream.CopyToAsync(ms);
            ms.Position = 0;
            return ms.ToArray();
        }
    }
}
